from django.shortcuts import render

from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.http import FileResponse
from django.template import RequestContext
from django.urls import reverse
from django.utils.http import urlquote
 
from .models import FileInfo
from .forms import UploadForm
import os
from django.conf import settings
import json
import datetime
 
# 上传文件
def upload(request):

    # Handle file upload
    if request.method == 'POST':

        file = request.FILES.get('file', None)
        if file is None:
            return HttpResponse("no files for upload!")
        else:

       # for f in files:
         #   file_info = FileInfo(file_name=f.name, file_size=1 if 0 < f.size < 1024 else f.size / 1024, file_path=os.path.join('/root/Code/Python/safetyhelmetdetect/upload', f.name))
         #   file_info.save()
         ##存数据库
            file_info = FileInfo(file_name=file.name, file_size=1 if 0 < file.size < 1024 else file.size / 1024, file_path=os.path.join(settings.BASE_DIR, 'upload/' + file.name))
            file_info.save()

        # 上传
            destination = open(os.path.join(settings.BASE_DIR, 'upload/' + file.name), 'wb+')
            for chunk in file.chunks():
                destination.write(chunk)
            destination.close()
 
            # 返回上传页
            return HttpResponseRedirect('/uploader/list')
            #return render(request, 'uploader/ok.html')
    else:
        form = UploadForm() # A empty, unbound form
        return render(request, 'uploader/upload.html', {'form': form})
    
 
# 文件列表
def list(request):

    file_infos = FileInfo.objects.all()

    return render(request, 'uploader/list.html', {'file_infos': file_infos})

 

# 进行目标检测
def detect(request):
    cmd = "{py} {detect} --source {source} --weights {weights} --project {project} --name {name}"
    py = os.path.join(settings.YOLO_ENV_PATH,'bin/python')
    detect = os.path.join(settings.YOLO_PRO_PATH, 'detect.py')
    source = request.POST['file_path']
    weights = os.path.join(settings.YOLO_PRO_PATH, 'weights/safety_helmet.pt')
    project = os.path.join(settings.BASE_DIR, 'runs/detect')
    name = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
    fmt_cmd = cmd.format(py=py, detect=detect, source=source, weights=weights, project=project, name=name)

    if os.system(fmt_cmd) == 0:
        detect_result = 'detect/'+ name + '/' + request.POST['file_name']
        return HttpResponse(detect_result)
    else:
        #待改进，需要返回失败原因
        return HttpResponse("detect faild")



# 下载文件
def download(request):
    #file_info = FileInfo.objects.get(id=id)
    #print('下载的文件名：' + file_info.file_name)
    
    file_name = request.GET['download_path']
    file_path = os.path.join(settings.BASE_DIR, 'runs/') + file_name
    print(file_path)
    file = open(file_path, 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="%s"' % urlquote(file_name)
    return response
    
 
# 删除文件
def delete(request, id):
    file_info = FileInfo.objects.get(id=id)
    file_info.delete()
    file_infos = FileInfo.objects.all()
 
    return HttpResponseRedirect('/uploader/list')